package cn.iocoder.yudao.module.reading.dal.mysql.community;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.reading.controller.app.community.vo.post.PostPageReqVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.community.CommunityPostDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Component;

/**
 * 社区帖子 Mapper
 *
 * @author 芋道源码
 */
@Mapper
@Component("communityPostMapper")
public interface CommunityPostMapper extends BaseMapperX<CommunityPostDO> {

    /**
     * 分页查询帖子列表
     */
    default PageResult<CommunityPostDO> selectPage(PostPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<CommunityPostDO>()
                .eqIfPresent(CommunityPostDO::getType, reqVO.getType())
                .eqIfPresent(CommunityPostDO::getUserId, reqVO.getUserId())
                .eqIfPresent(CommunityPostDO::getIsHot, reqVO.getOnlyHot())
                .eqIfPresent(CommunityPostDO::getIsTop, reqVO.getOnlyTop())
                .and(reqVO.getKeyword() != null, w -> w
                        .like(CommunityPostDO::getTitle, reqVO.getKeyword())
                        .or()
                        .like(CommunityPostDO::getContent, reqVO.getKeyword()))
                .eq(CommunityPostDO::getStatus, 1) // 只查询正常状态的帖子
                .orderByDesc(CommunityPostDO::getIsTop) // 置顶帖子优先
                .orderByDesc(CommunityPostDO::getCreateTime)); // 按创建时间倒序
    }

    /**
     * 增加帖子点赞数
     */
    @Update("UPDATE community_posts SET like_count = like_count + #{increment} WHERE id = #{postId}")
    void updateLikeCount(@Param("postId") Long postId, @Param("increment") Integer increment);

    /**
     * 增加帖子评论数
     */
    @Update("UPDATE community_posts SET comment_count = comment_count + #{increment} WHERE id = #{postId}")
    void updateCommentCount(@Param("postId") Long postId, @Param("increment") Integer increment);

    /**
     * 增加帖子浏览数
     */
    @Update("UPDATE community_posts SET view_count = view_count + 1 WHERE id = #{postId}")
    void updateViewCount(@Param("postId") Long postId);

}
